package cn.yuxiaoyuan.system.controller;

import cn.yuxiaoyuan.annotation.PreAuthorize;
import cn.yuxiaoyuan.system.domain.Employee;
import cn.yuxiaoyuan.system.query.EmployeeQuery;
import cn.yuxiaoyuan.system.service.EmployeeService;
import cn.yuxiaoyuan.system.vo.EmployeeVo;
import cn.yuxiaoyuan.utils.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PreAuthorize(sn = "employee:findById",name = "根据id查询员工",descs = "根据id查询员工")
    @GetMapping("/{id}")
    public R findById(@PathVariable("id") Long id) {
        return R.ok(employeeService.findById(id));
    }

    @PreAuthorize(sn = "employee:findAll",name = "查询所有员工",descs = "查询所有员工")
    @GetMapping
    public R findAll() {
        return R.ok(employeeService.findAll());
    }

    @PreAuthorize(sn = "employee:deleteById",name = "根据id删除员工",descs = "根据id删除员工")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable("id") Long id) {
        employeeService.deleteById(id);
        return R.ok();
    }

    @PreAuthorize(sn = "employee:deleteAll",name = "根据ids删除员工",descs = "根据ids删除员工")
    @PostMapping("/deleteAll")
    public R batchDelete(@RequestBody List<Long> ids) {
        employeeService.batchDelete(ids);
        return R.ok();
    }

    @PreAuthorize(sn = "employee:add",name = "添加和修改员工",descs = "添加和修改员工")
    @ApiOperation("添加和修改")
    @PostMapping
    public R add(@RequestBody EmployeeVo employeeVo) {
        if (employeeVo.getId() == null) {
            employeeService.add(employeeVo);
        } else {
            employeeService.update(employeeVo);
        }
        return R.ok();
    }

    @PreAuthorize(sn = "employee:getPage",name = "员工的分页查询",descs = "员工的分页查询")
    @PostMapping("/page")
    public R getPage(@RequestBody EmployeeQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<Employee> employees = employeeService.queryPage(query);
        PageInfo<Employee> pageInfo = new PageInfo<>(employees);
//        pageInfo.setTotal(employeeService.queryPageCount(query));
        return R.ok(pageInfo);
    }
}
